package TryCode.UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;

public class UDPServer {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket对象，指定监听的端口号
            DatagramSocket serverSocket = new DatagramSocket(5000,InetAddress.getByName("localhost"));

            byte[] receiveData = new byte[1024];

            while (true) {
                // 创建接收数据的DatagramPacket对象
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收客户端发送的数据
                serverSocket.receive(receivePacket);

                // 从接收的数据包中获取数据
                String clientMessage = new String(receivePacket.getData());

                // 获取客户端的IP地址和端口号
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                System.out.println("Received from client: " + clientMessage.replace("\u0000",""));

                // 发送响应给客户端
                String serverResponse = "Hello from server";
                byte[] sendData = serverResponse.getBytes();

                // 创建发送数据的DatagramPacket对象
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);

                // 发送数据包给客户端
                serverSocket.send(sendPacket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
